from core.Operation_DB.SqlLite_DB import sqliteDatabase

# 实例化sqliteDatabase
db = sqliteDatabase()


def migrate_data():
    try:
        # 创建新表
        db.execute_SQL("""
        CREATE TABLE api_data_new (
            id VARCHAR(17) NOT NULL, 
            api_name VARCHAR(64) NOT NULL, 
            url_path VARCHAR(255) NOT NULL, 
            template VARCHAR(255) NOT NULL, 
            description TEXT, 
            time DATETIME DEFAULT CURRENT_TIMESTAMP, 
            PRIMARY KEY (id), 
            UNIQUE (api_name), 
            UNIQUE (id), 
            UNIQUE (url_path)
        )
        """)

        # 迁移数据
        db.execute_SQL("""
        INSERT INTO api_data_new (id, api_name, url_path, template, description)
        SELECT id, api_name, url_path, template, description
        FROM api_data
        """)

        # 重命名表
        db.execute_SQL("ALTER TABLE api_data RENAME TO api_data_old")
        db.execute_SQL("ALTER TABLE api_data_new RENAME TO api_data")

        print("数据迁移成功")
    except Exception as e:
        print(f"数据迁移失败: {str(e)}")
        # 回滚操作
        SQL = "DROP TABLE IF EXISTS api_data_new"
        db.execute_SQL(SQL)
        db.execute_SQL("ALTER TABLE api_data_old RENAME TO api_data")


if __name__ == "__main__":
    migrate_data()